import { useState, useEffect } from 'react';
import request from '@/utils/request';
import omit from 'lodash/omit';
import PubSub from 'pubsub-js';

const eventName = 'useSlickTable';

const useSlickTable = (_params, _url, _form, _paginations) => {
  const defaultParams = { pageNum: 1, pageSize: 10, sortName: '', sortOrder: 'asc' };
  const defaultPagination = { current: 1, pageSize: 10 };
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [params, setParams] = useState({ ...defaultParams, ..._params });
  const [pagination, setPagination] = useState({
    ...defaultPagination,
    ..._params,
    ..._paginations,
  });

  const onRest = () => {
    _form.gb_reset = false;
  };

  const handleChange = (pagination, filters, sorter) => {
    onRest();
    setParams({
      ...params,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      sortName: sorter.field,
      sortOrder: sorter.order,
    });
  };

  useEffect(() => {
    let dataParamsObj = {};
    if (_form.gb_reset) {
      _form = omit(_form, ['gb_reset']);
      dataParamsObj = { ..._form, ...params, pageNum: 1 };
    } else {
      _form = omit(_form, ['gb_reset']);
      dataParamsObj = { ..._form, ...params };
    }

    setLoading(true);
    request(_url, {
      data: dataParamsObj,
    }).then(res => {
      setLoading(false);
      const { list } = res;
      let listArray = [];
      list.map(item => {
        if (item.hasOwnProperty('children')) {
          const obj = omit(item, ['children']);
          listArray.push(obj);
        } else {
          listArray = list;
        }
        return listArray;
      });
      setData(listArray);
      setPagination({
        ...pagination,
        current: res.pageNum,
        pageSize: res.pageSize,
        total: res.total,
        pageSizeOptions: ['5', '10', '15', '20'],
      });
    });
  }, [params, _form]);

  const result = {
    tableProps: {
      loading,
      data: {
        list: data,
        pagination,
      },
      onChange: handleChange,
    },
  };
  return result;
};

export default useSlickTable;
